import json

import openai
import os

from utils.log_util import logger
from utils.tts_ws_utils import Ws_Param
from userconfig import get_user_conf

context = ""
def gpt_stream(question):

    # openai.api_key = os.getenv("OPENAI_API_KEY")
    openai.api_key = get_user_conf('openai_api_key')
    global context

    try:
        result = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "user", "content": question},
                # {"role": "assistant", "content": context}
            ],
            temperature=0.7,
            stream=True,
        )

        for chunk in result:
            if chunk["choices"][0]["finish_reason"] is not None: # type: ignore
                data = "[DONE]"
            else:
                data = chunk["choices"][0]["delta"].get("content", "") # type: ignore
                # context += data
            yield "data: %s\n\n" % data.replace("\n", "<br />")
    except Exception as e:
        logger.warning(e)

    # return Ws_Param.content_gpt(context)
    # context = ""
